/*
 * The MIT License (MIT)
 * Copyright (c) 2025. Archermind Technology(Nanjing) CO., LTD.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import convertxml from '@ohos.convertxml';
import { LogUtil } from '../utils/log-util'

/**
 * '@ohos.convertxml的fastConvertToJSObject方法如果指定了命名空间转换后会忽略命名空间，
 *  目前规避方案：转换前先删除命名空间的申明
 * @param xmlstr
 * @returns
 */
function convertXmlToObject(xmlstr) {
    if (!xmlstr) {
        LogUtil.info("convertXmlToObject xmlstr is null");
        return {}
    }
    // trim: false 转换后是否删除文本前后的空格，否
    // declarationKey: "_declaration" 转换后文件声明使用_declaration来标识
    // instructionKey: "_instruction" 转换后指令使用_instruction标识
    // attributesKey: "_attributes" 转换后属性使用_attributes标识
    // textKey: "_text" 转换后标签值使用_text标识
    // cdataKey: "_cdata" 转换后未解析数据使用_cdata标识
    // docTypeKey: "_doctype" 转换后文档类型使用_doctype标识
    // commentKey: "_comment" 转换后注释使用_comment标识
    // parentKey: "_parent" 转换后父类使用_parent标识
    // typeKey: "_type" 转换后元素类型使用_type标识
    // nameKey: "_name" 转换后标签名称使用_name标识
    // elementsKey: "_elements" 转换后元素使用_elements标识
    let options = {
        trim: false,
        declarationKey: "_declaration",
        instructionKey: "_instruction",
        attributesKey: "_attributes",
        textKey: "_text",
        cdataKey: "_cdata",
        doctypeKey: "_doctype",
        commentKey: "_comment",
        parentKey: "_parent",
        typeKey: "_type",
        nameKey: "_name",
        elementsKey: "_elements"
    }

    let replacedXmlString = xmlstr.replace(/xmlns(:\w+)?=["'][^"']+["']/g, '');
    let conv = new convertxml.ConvertXML();
    let result = conv.fastConvertToJSObject(replacedXmlString, options);
    return result;
}

export { convertXmlToObject, }